#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2021/3/26 17:04
# @Author    :cjw
"""
requests.get() 同步代码 -> 异步操作aiohttp
需要安装：pip install aiohttp
"""
import asyncio
import aiohttp
import aiofiles

urls = [
	'http://kr.shanghai-jiuxin.com/file/2020/1031/191468637cab2f0206f7d1d9b175ac81.jpg',
	'http://kr.shanghai-jiuxin.com/file/2020/1031/774218be86d832f359637ab120eba52d.jpg',
	'http://kr.shanghai-jiuxin.com/file/2020/1031/eb2df41e2919e0b72878508ac4da08ea.jpg',
	'http://kr.shanghai-jiuxin.com/file/2020/1031/d7de3f9faf1e0ecdea27b73139fc8d3a.jpg',
	'http://kr.shanghai-jiuxin.com/file/2020/1031/a2c58d6d726fb7ef29390becac5d8643.jpg'
]
headers = {
	'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'
}


async def download(url: str):
	# aiohttp.ClientSession()  # 等价于requests
	name = url.rsplit('/', 1)[1]
	async with aiohttp.ClientSession() as session:
		# 1、发送请求
		async with session.get(url, headers=headers) as resp:
			# 2、请求得到响应内容，写入文件
			pic_content = await resp.content.read()
			async with aiofiles.open(f'./image/{name}', 'wb') as f:
				await f.write(pic_content)
	print(url, '图片保存成功！')


async def main():
	# 任务加载
	tasks = [asyncio.create_task(download(url)) for url in urls]
	await asyncio.wait(tasks)
	print('执行完成！')


if __name__ == '__main__':
	asyncio.run(main())
